package cn.yunhe.control;

import cn.yunhe.entity.Admin;
import cn.yunhe.server.AdminServer;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

public class AdminAction extends ActionBase {
    private String username;
    private String password;
    private Admin admin;
    private String result;

    public String login() {
       /* Subject subject = SecurityUtils.getSubject(); //shiro框架代码
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getAname(),admin.getApass());
        try {
            subject.login(token);
            return SUCCESS;
        }catch (Exception e){
            return ERROR;
        }*/
        AdminServer adminServer = new AdminServer();
        Admin loginAdmin = adminServer.Login(admin); //使用获取的admin进行登录验证
        Map session = getMapSession();
        Map request = getMapRequest();
        if (loginAdmin == null) { //若获取用户对象不为空说明存在该用户,登录成功,反之登录失败返回失败界面
            request.put("result", "用户名或密码不正确<a href='javascript:history.go(-1)'>返回上一级</a>");
            return ERROR;
        } else {
            session.put("admin", loginAdmin);
            return SUCCESS;
        }
    }

    public String getAllAdmin(){
        AdminServer adminServer = new AdminServer();
        List<Admin> list = adminServer.getAllAdmin(); //获取所有管理员对象
        String jsonList = JSON.toJSONString(list); //将集合转换成JSON格式
        setResult(jsonList);
        return SUCCESS;
    }

    public String logout(){
        Map session = getMapSession();
        session.put("admin", null);
        return SUCCESS;
    }

    public String reg(){
        AdminServer adminServer =new AdminServer();
        boolean flag = adminServer.register(username, password);
        if (flag){
            return SUCCESS;
        }else {
            Map request = getMapRequest();
            request.put("result", "注册失败<a href='javascript:go(-1)'>返回</a>");
            return ERROR;
        }
    }

    public Admin getAdmin() {
        return admin;
    }

    public void setAdmin(Admin admin) {
        this.admin = admin;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
